/*
 *  $Id: Dice.cs 172 2008-04-11 16:03:55Z thenn.erannor $
 *	This file is a part of Ragima CCG.
 *	(C) 2008 Ragima development group.
 *
 *	Licensed under the terms of the GNU GPL License version 2.
 *
 */

using System;

namespace Ragima {
    public class Dice {
        private static readonly int[] ValueAngles = {0, 0, 300, 180, 60, 120, 240};
        private const int DefaultStep = 1;
        private const int FastStep = 5;
        private const int OverStep = 4;
        private const int MinDistance = 120;

        private int _angle;
        private int _value;
        private bool _over, _overdir;
        private int _overpos;
        private int _steps;

        public Dice() {
            _angle = 0;
            _value = 0;
            _over = false;
            _overpos = 0;
        }

        public int Value { get { return _value; } }
        private int ValueAngle { get { return ValueAngles[_value]; } }
        public bool IsAnchored { get { return _steps == 0 && !_over && ValueAngle == _angle; } }

        public void Draw() {
            Data.Dice.RotationAngleDegrees = _angle;
            Data.Dice.Draw(Constants.DiceCenterX, Constants.DiceCenterY);
            if (_over)
                Data.DiceOver.Draw(Constants.DiceOverX, Constants.DiceOverY + Constants.DiceOverSize - _overpos);
        }

        public void Process() {
            if (Value == 0) {
                 _angle = (_angle + DefaultStep) % 360;
                return;
            }
            if (!_over) return;
            if (_overdir) {
                if (_steps > 0) {
                    _angle = (_angle + FastStep) % 360;
                    _steps--;
                    if (_steps == 0) _angle = ValueAngle;
                    return;
                }
                _overpos -= OverStep;
                if (_overpos <= 0) _over = false;
            } else {
                 _angle = (_angle + DefaultStep) % 360;
                _overpos += OverStep;
                if (_overpos >= Constants.DiceOverSize) {
                    _overpos = Constants.DiceOverSize;
                    int dist = ValueAngle - _angle;
                    while (dist < MinDistance) dist += 360;
                    _steps = dist / FastStep;
                    _overdir = true;
                }
                return;
            }
        }

        public void Next(Randomizer random) {
            _value = random.Next(6) + 1;
            _over = true;
            _overdir = false;
        }
        public void Reset() {
            _value = 0;
        }
    }
}